package com.lagou.webwork.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author sjp
 * @date 2021/5/26 18:15
 * @description
 */
public class DruidUtils {
    /**
     * 定义资源池(数据库连接池)
     */
    private static DataSource dataSource;

    static{
        try {
            //1.读取Druid资源文件的数据
            Properties properties = new Properties();
            InputStream resourceAsStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(resourceAsStream);

            //2.赋值给dataSource对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取资源连接池对象(数据库连接池)
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 获取数据库连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭连接
     * @param con 连接对象
     * @param statement 数据库执行对象
     * @throws SQLException
     */
    public static void close(Connection con, Statement statement) throws SQLException {
        if (null!=statement){
            statement.close();
        }
        if (null!=con){
            con.close();
        }
    }

    /**
     * 关闭连接
     * @param con 连接对象
     * @param statement 数据库执行对象
     * @param resultSet 结果集对象
     * @throws SQLException
     */
    public static void close(Connection con, Statement statement, ResultSet resultSet) throws SQLException {
        if (null!=resultSet){
            resultSet.close();
        }
        if (null!=statement){
            statement.close();
        }
        if (null!=con){
            con.close();
        }
    }
}
